import { useMemoizedFn, useMount, useReactive, useSafeState } from "ahooks";
import type { GlobalModelState } from "@/ui/context";
import * as rpc from "@/ui/utils/rpc";
import { toast } from "sonner";
import events from "@/ui/events";
import { Form, message } from "antd";
import * as apis from "@/ui/utils/backend";
import { ResCode } from "@/ui/utils/backend/meta";
import { encrypt } from "@/ui/utils/crypto";

export const useViewModel = () => {
  const [loading, setLoading] = useSafeState(true);
  const [logining, setLogining] = useSafeState(false);
  const [hasRHChromium, setHasRHChromium] = useSafeState(true);
  const globalModel = useReactive<GlobalModelState>({
    sessions: [],
    profiles: [],
    quickMessages: [],
    inputMode: "normal",
    emojis: [],
  });
  const form = Form.useForm<{
    name: string;
    password: string;
    saveAuth: boolean;
    autoLogin: boolean;
  }>()[0];

  (window as any).globalModel = globalModel;

  const loadAccounts = useMemoizedFn(async () => {
    const { profiles } = await rpc.loadBrowserProfiles();
    const { sessions } = await rpc.syncBrowserSessions();
    globalModel.sessions = sessions;
    globalModel.profiles = profiles;
  });

  const init = useMemoizedFn(async () => {
    setLoading(true);
    setTimeout(async () => {
      await loadAccounts();
      const result = await rpc.hasRHChromium();
      setHasRHChromium(result);
      setLoading(false);
    }, 1000);

    events.Global.Plugin.Exit.on(async ({ pluginId }) => {
      await loadAccounts();
      const user = globalModel.profiles.find((p) => p.id === pluginId)?.xhsUser;
      if (!user) {
        toast("取消登录");
      } else {
        toast(`账号【${user.nickname}】退出登录`);
      }
    });
  });

  const onLoginClick = useMemoizedFn(async () => {
    if (globalModel.userCheckTaskId) {
      clearInterval(globalModel.userCheckTaskId);
      delete globalModel.userCheckTaskId;
    }

    setLogining(true);
    try {
      const data = await form.validateFields();
      {
        const ret = (await apis.user.login(data)).data;
        if (ret.code) {
          if (ret.code === ResCode.AUTH_ERR) {
            message.error("登录失败：账号密码不一致");
          } else {
            const tip = `登录失败：${ret.msg}`;
            message.error(tip);
            console.error(tip, ret);
          }
          return setLogining(false);
        }
      }
      {
        const ret = (await apis.user.get()).data;
        if (ret.code) {
          message.error(`登录失败：${ret.msg}`);
          console.error(`登录失败：${ret.msg}`, ret);
          return setLogining(false);
        }

        if (!data.saveAuth) {
          await rpc.settings.set("XHM_USER_NAME", "");
          await rpc.settings.set("ASDF", "");
          await rpc.settings.set("XHM_USER_AUTO_LOGIN", "false");
          await rpc.settings.set("XHM_USER_SAVE_AUTH", "false");
        } else {
          await rpc.settings.set("XHM_USER_NAME", data.name);

          const pw = encrypt(data.password, ret.data.hashId + ret.data.name);
          await rpc.settings.set(
            "ASDF",
            btoa([ret.data.email, pw, ret.data.hashId].join(";")),
          );
          await rpc.settings.set(
            "XHM_USER_AUTO_LOGIN",
            data.autoLogin ? "true" : "false",
          );
          await rpc.settings.set("XHM_USER_SAVE_AUTH", "true");
        }

        if (!ret.data.validEnd) {
          // 永久有效
          globalModel.user = ret.data;
          return setLogining(false);
        }

        if (ret.data.validEnd < Date.now()) {
          message.error(`许可已过期`);
        } else {
          globalModel.user = ret.data;
          globalModel.userCheckTaskId = setInterval(
            async () => {
              const ret = (await apis.user.get()).data;
              if (ret.code) {
                if (ret.code === ResCode.NEED_LOGIN) {
                  console.error("登录过期，请重新登录");
                  clearInterval(globalModel.userCheckTaskId);
                  delete globalModel.user;
                  delete globalModel.userCheckTaskId;
                } else {
                  console.error("服务异常：", ret);
                }
              } else if (ret.data.validEnd < Date.now()) {
                message.error(`许可已过期`);
                clearInterval(globalModel.userCheckTaskId);
                delete globalModel.userCheckTaskId;
                delete globalModel.user;
              } else if (ret.data.validEnd !== globalModel.user?.validEnd) {
                globalModel.user = ret.data;
              }
            },
            1000 * 60 * 5,
          );
          events.XHM.USER.LOGIN.emit({ user: { ...ret.data } });
        }
        setLogining(false);
      }
    } catch (err) {
      setLogining(false);
      console.error(err);
    }
  });

  useMount(init);

  return {
    form,
    loading,
    globalModel,
    hasRHChromium,
    logining,

    onLoginClick,
  };
};
